package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import feces.Database;
import feces.filter.LoginFilter;
import feces.model.User;
import feces.utility.IO;
import lombok.Getter;
import lombok.NoArgsConstructor;

@WebServlet(name = "login_servlet", urlPatterns = { "/login" })
@NoArgsConstructor
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 5677344875190912616L;
	
	public static final String URL_LOGIN = "/login.html";
	
	public static final String URL_INDEX = "/index.html";
	
	@Getter
	public String prefix;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		prefix = config.getServletContext().getContextPath();
		IO.printf("prefix: %s\n", prefix);
	}

	@Override
	public void doPost(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(LoginFilter.KEY_USER);
		if (user == null) {
			String id = request.getParameter("id");
			String password = request.getParameter("password");
			if (id == null || password == null) {
				response.sendRedirect(getPrefix() + URL_LOGIN);
				return;
			}
			List<User> users = Database.executeQuery(
				"SELECT u FROM User u WHERE u.id = ?1 AND u.password = ?2",
				User.class, id, password
			);
			if (users.size() != 1) {
				response.sendRedirect(getPrefix() + URL_LOGIN);
				return;
			}
			user = users.get(0);
		}
		session.setAttribute(LoginFilter.KEY_USER, user);
		response.sendRedirect(getPrefix() + URL_INDEX);
	}

}
